package org.ims.inv.web.action.system;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.ims.inv.model.system.ModelAppProjectGroup;
import org.ims.inv.model.system.ModelAppUser;
import org.ims.inv.web.action.BaseAppAction;

import cn.trymore.core.exception.ServiceException;
import cn.trymore.core.util.UtilString;
import cn.trymore.core.web.paging.PaginationSupport;
import cn.trymore.core.web.paging.PagingBean;

/**
 * Action: 项目分组管理
 * 
 * @author Jeccy.Zhao
 *
 */
public class SystemGroupAction
extends BaseAppAction
{
	/**
	 * The LOGGER
	 */
	private static final Logger LOGGER = Logger.getLogger(SystemGroupAction.class);
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 项目分组列表
	 */
	public ActionForward pageGroupIndex (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String groupName = request.getParameter("groupName");
			String groupLeader = request.getParameter("gleader.username");
			String groupMember = request.getParameter("gmember.username");
			
			ModelAppProjectGroup criteria = new ModelAppProjectGroup();
			criteria.setGroupName(groupName);
			criteria.setGroupLeaders(groupLeader);
			criteria.setGroupMembers(groupMember);
			
			PagingBean pagingBean = this.getPagingBean(request);
			PaginationSupport<ModelAppProjectGroup> pagingData = 
					this.serviceAppProjectGroup.getPagination(criteria, pagingBean);
			
			request.setAttribute("datagrid", pagingData);
			this.outWriteAllParameters(request);
			this.outWritePagination(request, pagingBean, pagingData);
			
			request.setAttribute("groupLeader", groupLeader);
			request.setAttribute("groupMember", groupMember);
			
			return mapping.findForward("page.sys.group.index");
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading user dialog page", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 项目组配置弹框页面
	 */
	public ActionForward dialogGroupPage (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String id = request.getParameter("id");
			if (UtilString.isNotEmpty(id))
			{
				if (!this.isObjectIdValid(id))
				{
					return ajaxPrint(response, getErrorCallback("数据加载失败: 不合法的数据ID, " + id));
				}
				else
				{
					ModelAppProjectGroup entity = this.serviceAppProjectGroup.get(id);
					if (entity == null)
					{
						return ajaxPrint(response, getErrorCallback("数据加载失败: 数据实体不存在, " + id));
					}
					
					request.setAttribute("entity", entity);
				}
			}
			
			request.setAttribute("users", this.serviceAppUser.getAllUsers());
			return mapping.findForward("dialog.sys.group");
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading user dialog page", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 项目组保存
	 */
	public ActionForward actionSaveGroup (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String groupName = request.getParameter("groupName");
			String groupLeaders = request.getParameter("leaders");
			String groupMembers = request.getParameter("members");
			
			if (UtilString.isNotEmpty(groupName, groupLeaders, groupMembers))
			{
				if (groupLeaders.endsWith(","))
				{
					groupLeaders = groupLeaders.substring(0, groupLeaders.length() - 1);
				}
				
				if (groupMembers.endsWith(","))
				{
					groupMembers = groupMembers.substring(0, groupMembers.length() - 1);
				}
				
				ModelAppProjectGroup group = null;
				String groupId = request.getParameter("id");
				if (this.isObjectIdValid(groupId))
				{
					group = this.serviceAppProjectGroup.get(groupId);
					if (group == null)
					{
						return ajaxPrint(response, getErrorCallback("项目组不存在:" + groupId));
					}
				}
				else
				{
					group = new ModelAppProjectGroup();
					group.setGroupCreationTime(new Date());
				}
				
				group.setGroupName(groupName);
				group.setGroupLeaderIds(groupLeaders);
				group.setGroupLeaders(this.getMemberNamesBySet(groupLeaders, ","));
				group.setGroupMemberIds(groupMembers);
				group.setGroupMembers(this.getMemberNamesBySet(groupMembers, ","));
				
				group.setGroupUpdateTime(new Date());
				
				this.serviceAppProjectGroup.save(group);
				
				return ajaxPrint(response, 
						getSuccessCallback("数据保存成功.", CALLBACK_TYPE_CLOSE, CURRENT_NAVTABID, null, false));
			}
			else
			{
				return ajaxPrint(response, getErrorCallback("非法的表单输入参数.."));
			}
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when saving role data", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	/**
	 * 根据ID集合获取用户名
	 * 
	 * @param setText
	 * @param separator
	 * @return
	 * @throws ServiceException
	 */
	private String getMemberNamesBySet (String setText, String separator) throws ServiceException
	{
		List<String> memberNames = new ArrayList<String>();
		if (UtilString.isNotEmpty(setText))
		{
			String[] ids = setText.split(separator);
			for (String id : ids)
			{
				ModelAppUser user = this.serviceAppUser.get(id);
				if (user != null)
				{
					memberNames.add(user.getUsername());
				}
			}
		}
		
		return UtilString.join(memberNames, separator);
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 项目组删除
	 */
	public ActionForward actionRemoveGroup (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String groupId = request.getParameter("id");
			
			if (this.isObjectIdValid(groupId))
			{
				ModelAppProjectGroup entity = this.serviceAppProjectGroup.get(groupId);
				if (entity != null)
				{
					this.serviceAppProjectGroup.remove(entity);
					
					return ajaxPrint(response, 
							getSuccessCallback("项目组删除成功.", CALLBACK_TYPE_CLOSE, CURRENT_NAVTABID, null, false));
				}
				else
				{
					return ajaxPrint(response, getErrorCallback("项目组不存在:" + groupId));
				}
			}
			else
			{
				return ajaxPrint(response, getErrorCallback("不合法的项目组ID:" + groupId));
			}
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when saving role data", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	public static Logger getLogger()
	{
		return LOGGER;
	}
	
}
